import React from 'react'

import { useState } from 'react'

export default function App() {
    const [content, setContent] = useState('')
    const [question, setQuestion] = useState('讲一讲计算机操作系统的知识和学习建议')
    const [streaming, setStreaming] = useState(false)
    const update = async () => {
        if (!question) return
        setContent('思考中...')
        const endpoint = 'https://api.deepseek.com/chat/completions'
        const headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + import.meta.env.VITE_DEEPSEEK_API_KEY
        }
        const response =await fetch(endpoint,{
            method:'POST',
            headers,
            body:JSON.stringify({
                model:'deepseek-chat',
                messages:[{
                    role:'user',
                    content:question
                }],
                stream:streaming
            })
        })
        if(streaming){
            setContent('')
            const reader = response.body.getReader()
            const decoder = new TextDecoder()
            let done=false
            let buffer =''
            while(!done){
               const {value, done:doneReading} = await reader.read()
               done=doneReading
               buffer+=decoder.decode(value)
               setContent(buffer)
            }

        }else{
            const data =await response.json()
            setContent(data.choices[0].message.content)
        }
    }
    return (
        <div className='container'>
            <div>
                <label>输入</label>
                <input type="text" defaultValue={question} onChange={(e) => setQuestion(e.target.value)} />
                <button onClick={update}>提交</button>
            </div>
            <div className='output' style={{ minHeight: '300px', width: '500px' }}>
                <div>
                    <label>Streaming</label>
                    <input type="checkbox" onChange={(e) => setStreaming(e.target.checked)} />
                    <div>{content}</div>
                </div>
            </div>
        </div>
    )
}
